﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PortChat
{
    //frame generator
    class FrameGenerator
    {
        //to count the frames, it starts by 10000 to let the size of this field constant
        private static int intFrameNumber = 10000;
        //startflag of a frame 
        private String strStartFlag = "01111110";
        //endflag of a frame (equal with startFlag)
        private String strEndFlag = "01111110";
        //the string version of intFrameNumber
        private String strFrameNumber = "";
        //true if hanhshaking frame, otherwise false
        private String strHandshaking;
        //true if check word frame, otherwise false
        private String strCheckWord;
        //generates a frame with the message
        //handhacking == true means "Quittungs-" frame
        //FrameNummer | Handshaking | PayLoad
        //10000 | 0 | <COM1>: 000...
        public String generateFrame(String strMessageP, int iComPortName, Boolean bHandshakingP, Boolean bCheckWordP)
        {
            strFrameNumber = Convert.ToString(intFrameNumber);
            if(bHandshakingP)
            {
                strHandshaking = "1";
            } else 
            {
                strHandshaking = "0";
            }
            if (bCheckWordP)
            {
                strCheckWord = "1";
            } else
            {
                strCheckWord = "0";
            }
            String strCompPortName;
            switch (iComPortName)
            {
                case 0: strCompPortName = "0000"; break;
                case 1: strCompPortName = "0001"; break;
                case 2: strCompPortName = "0010"; break;
                case 3: strCompPortName = "0011"; break;
                case 4: strCompPortName = "0100"; break;
                case 5: strCompPortName = "0101"; break;
                case 6: strCompPortName = "0110"; break;
                case 7: strCompPortName = "0111"; break;
                case 8: strCompPortName = "1000"; break;
                case 9: strCompPortName = "1001"; break;
                case 10: strCompPortName = "1010"; break;
                case 11: strCompPortName = "1011"; break;
                case 12: strCompPortName = "1100"; break;
                case 13: strCompPortName = "1101"; break;
                case 14: strCompPortName = "1110"; break;
                case 15: strCompPortName = "1111"; break;
                default: strCompPortName = "1111"; break;
            }
            
            intFrameNumber = intFrameNumber + 1;

            return strFrameNumber + strHandshaking + strCheckWord + strCompPortName + strMessageP;

        }
        //adds the start flag and the end flag to the frame
        public String addStartEndFlag(String strFrame)
        {
            return strStartFlag + strFrame + strEndFlag;               
        }
    }
}
